package controller

import (
	"encoding/json"
	"fmt"
	"gitee.com/zhoulvvv/my_go_gateway/dto"
	"gitee.com/zhoulvvv/my_go_gateway/middleware"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"gitee.com/zhoulvvv/my_go_gateway/services"
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

type AdminController struct {
}

func RegisterAdminController(group *gin.RouterGroup) {
	admin := &AdminController{}
	group.GET("/admin_info", admin.AdminInfo)
	group.POST("/change_pwd", admin.ChangePwd)
}

// AdminInfo godoc
// @Summary 获取登录用户信息
// @Description 获取登录用户信息
// @Tags 用户接口
// @ID /admin/admin_info
// @Accept  json
// @Produce  json
// @Success 200 {object} middleware.Response{data=dto.AdminInfoOutput} "success"
// @Router /admin/admin_info [get]
func (admin *AdminController) AdminInfo(c *gin.Context) {
	// 从session中获取到数据
	sess := sessions.Default(c)
	sessionInfo := sess.Get(public.AdminSessionInfoKey)
	adminSessInfo := &dto.AdminSessionInfo{}
	// 反序列化
	if err := json.Unmarshal([]byte(fmt.Sprint(sessionInfo)), adminSessInfo); err != nil {
		middleware.ResponseError(c, 2000, err)
		return
	}
	out := &dto.AdminInfoOutput{
		ID:           adminSessInfo.ID,
		Name:         adminSessInfo.UserName,
		LoginTime:    adminSessInfo.LoginTime,
		Avatar:       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
		Introduction: "测试用户信息",
		Roles:        []string{"admin"},
	}
	middleware.ResponseSuccess(c, out)
}

// ChangePwd godoc
// @Summary 修改密码
// @Description 修改密码
// @Tags 用户接口
// @ID /admin/change_pwd
// @Accept  json
// @Produce  json
// @Param body body dto.ChangePwdInput true "body"
// @Success 200 {object} middleware.Response{data=string} "success"
// @Router /admin/change_pwd [post]
func (admin *AdminController) ChangePwd(c *gin.Context) {

	params := &dto.ChangePwdInput{}
	if err := params.BindValidaParam(c); err != nil {
		middleware.ResponseError(c, 2000, err)
		return
	}

	// 从session中获取到数据
	sess := sessions.Default(c)
	sessionInfo := sess.Get(public.AdminSessionInfoKey)
	adminSessInfo := &dto.AdminSessionInfo{}
	// 反序列化
	if err := json.Unmarshal([]byte(fmt.Sprint(sessionInfo)), adminSessInfo); err != nil {
		middleware.ResponseError(c, 2000, err)
		return
	}
	// 从数据库中获取用户信息
	adminService, err := services.NewAdminService()
	if err != nil {
		middleware.ResponseError(c, 2000, err)
		return
	}
	adminDB, err := adminService.GetUserInfoById(c, adminSessInfo.ID)
	if err != nil {
		middleware.ResponseError(c, 2000, err)
		return
	}
	// 使用数据库存储的盐值+前端传递的密码，然后对密码进行加密
	saltPass := public.GenSaltPassword(adminDB.Salt, params.Password)
	adminDB.Password = saltPass
	// 修改用户信息
	if err := adminService.Update(c, adminDB); err != nil {
		middleware.ResponseError(c, 2000, err)
		return
	}
	middleware.ResponseSuccess(c, "成功修改密码")
}
